﻿Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.IO
Imports System.Management
Imports System.Diagnostics
Imports System.ComponentModel
Imports Microsoft.Web.Administration
Imports Microsoft.Web.Management
Imports System.Security
Imports System.Windows.Forms
Imports System.Net.NetworkInformation
Imports System.Net
Imports System.Xml
Imports System.Data.SqlClient

Public Class TimedWebClient
    Inherits WebClient
    Public Property Timeout() As Integer
        Get
            Return m_Timeout
        End Get
        Set(value As Integer)
            m_Timeout = value
        End Set
    End Property
    Private m_Timeout As Integer
    Public Sub New()

        Me.Timeout = 60000
    End Sub

    Protected Overrides Function GetWebRequest(address As Uri) As WebRequest
        Dim objWebRequest = MyBase.GetWebRequest(address)
        objWebRequest.Timeout = Me.Timeout
        Return objWebRequest
    End Function
End Class

'For this class Will need to pass certain parameters to each function a sample of their calls are place before each function
Public Class wmi22

    Private Const MSSystem As String = "\C$\SecretAgent\wwwRoot\IncludeDirectories\Mastersite\System\"

    Private Shared Sub RunProcess(ServerName As String, process As String)
        Dim theProcessToRun As Object() = {process}
        Dim mClass As New ManagementClass("\\" & ServerName & "\root\cimv2:Win32_Process")
        Dim result As Object = mClass.InvokeMethod("Create", theProcessToRun)
    End Sub

    'This will reset the IIS for the server. 
    '   wmi22.IISReset(Sev_box.Text)
    Public Shared Function IISReset(ServerName As String) As [Boolean]
        Try
            RunProcess(ServerName, "iisreset.exe")
            Return True
        Catch
            Return False
        End Try
    End Function

    'Takes server offline
    'wmi22.ServerOffline(Sev_box.Text)
    Public Shared Function ServerOffline(ServerName As String) As [Boolean]
        Try
            ServerName = "\\" & ServerName
            File.SetAttributes(ServerName & MSSystem & "Status.aspx", FileAttributes.Normal)
            File.Delete(ServerName & MSSystem & "Status.aspx")
            File.Copy(ServerName & MSSystem & "StatusFail.aspx", ServerName & MSSystem & "Status.aspx")
            Return True
        Catch
            Return False
        End Try
    End Function

    'Brings server online
    'wmi22.ServerOnline(Sev_box.Text)
    Public Shared Function ServerOnline(ServerName As String) As [Boolean]
        Try
            ServerName = "\\" & ServerName
            File.SetAttributes(ServerName & MSSystem & "Status.aspx", FileAttributes.Normal)
            File.Delete(ServerName & MSSystem & "Status.aspx")
            File.Copy(ServerName & MSSystem & "StatusOriginal.aspx", ServerName & MSSystem & "Status.aspx")

            Return True
        Catch
            Return False
        End Try
    End Function

    'This method export registry to file. 
    'wmi22.ExportReg("HKEY_LOCAL_MACHINE\\Software\\RCI", "C:\\myLocal.reg", Servers.Text)
    Public Shared Function ExportReg(RegKey As String, SavePath As String, ServerName As String) As [Boolean]
        Dim path As String = """" & SavePath & """"
        Dim key As String = """" & RegKey & """"
        Dim process As String = "regedit.exe /e " & path & " " & key & ""
        Try
            RunProcess(ServerName, process)
            Return True
        Catch
            Return False
        End Try
    End Function

    'This method imports the registry file 
    '
    Public Shared Function ImportReg(RegKey As String, SavePath As String, ServerName As String) As [Boolean]
        Dim path As String = """" & SavePath & """"
        Dim key As String = """" & RegKey & """"
        Dim process As String = "regedit.exe /s " & path & " " & key & ""
        Try
            RunProcess(ServerName, process)
            Return True
        Catch
            Return False
        End Try
    End Function

    'Pulls the performance counter for that specfic server. 
    'wmi22.PerformanceMonitor(FullComputerName, Name, PW, "1" -"6")
    Public Shared Function PerformanceMonitor(FullComputerName As String, Name As String, PW As String, counter As String) As String

        Dim ReturnCounter As String = ""
        Try
            Dim connection As New ConnectionOptions()
            connection.Username = Name
            connection.Password = PW
            connection.Authority = "ntlmdomain:ENEIGHBORHOODS"

            Dim scope As New ManagementScope("\\" & FullComputerName & "\root\CIMV2", connection)
            scope.Connect()

            Dim query As New ObjectQuery("SELECT * FROM Win32_PerfRawData_ASPNET_ASPNETApplications")
            Dim query1 As New ObjectQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory")
            Dim query2 As New ObjectQuery("SELECT * FROM Win32_PerfRawData_PerfDisk_PhysicalDisk")

            Dim searcher As New ManagementObjectSearcher(scope, query)



            For Each queryObj As ManagementObject In searcher.[Get]()
                If counter = "1" Then
                    '"AnonymousRequests : {0}"
                    ReturnCounter = (queryObj("AnonymousRequests").ToString())
                    '"AnonymousRequests : {0}"
                    Debug.WriteLine(queryObj("AnonymousRequests"))
                    Exit For
                End If

                If counter = "2" Then
                    '"RequestExecutionTime : {0}"
                    ReturnCounter = (queryObj("RequestExecutionTime").ToString())
                    Exit For
                End If

                If counter = "3" Then
                    '"RequestWaitTime : {0}"
                    ReturnCounter = (queryObj("RequestWaitTime").ToString())
                    Exit For
                End If

                If counter = "4" Then
                    '"AnonymousRequestsPerSec : {0}"
                    ReturnCounter = queryObj("AnonymousRequestsPerSec").ToString()
                    Exit For
                End If

                If counter = "5" Then
                    ' "SessionActive : {0}"
                    ReturnCounter = queryObj("SessionActive").ToString()
                    Exit For
                End If
            Next



            If counter = "6" Then
                Dim searcher3 As New ManagementObjectSearcher(scope, query2)


                For Each queryObj As ManagementObject In searcher3.[Get]()

                    If True Then
                        '"AvgDiskQueueLength : {0} "
                        ReturnCounter = queryObj("AvgDiskQueueLength").ToString()
                        Exit For
                    End If
                Next
            End If




        Catch err As ManagementException

            ReturnCounter = err.Message.ToString()
        End Try

        Return ReturnCounter
    End Function

    'Connects to the Database NFDBCONFIF\\CONFIG
    'wmi22.Datapod
    Public Shared Function Datapod() As List(Of String)
        'Initating a new list for the ilist the combo box takes. 
        Dim VBAT3 As New List(Of String)()
        Dim queryString As String = "usp_Get_WebDronePair;"
        Dim thisconnection As New SqlConnection("Data Source=NFDBCONFIG\CONFIG;" & "Initial Catalog=Customers;" & "user id=rciapplicationsnew;" & "password=H7hr89jz?")

        If True Then

            Dim command As New SqlCommand(queryString, thisconnection)
            thisconnection.Open()

            Dim reader As SqlDataReader = command.ExecuteReader()

            While reader.Read()


                VBAT3.Add(reader("WebServerName").ToString())
            End While

            thisconnection.Close()

        End If
        Return VBAT3
    End Function

    'Web Server Status. 
    'wmi22.CheckPool(Server.Text)
    Public Shared Function CheckPool(FullComputerName As String) As String
        Dim ResponseWebSite As String = " "
        Dim WebSiteLink As String
        Dim html As String = " "


        Try

            WebSiteLink = "http://" & FullComputerName.ToLower() & "/system/status.aspx"

            html = New TimedWebClient() With {.Timeout = 5000}.DownloadString(WebSiteLink)

        Catch generatedExceptionName As WebException
            WebSiteLink = "http://www." & FullComputerName.ToLower() & ".com/system/status.aspx"

            html = New TimedWebClient() With {.Timeout = 150000}.DownloadString(WebSiteLink)
        End Try

        Try


            Dim intPos As Integer = html.IndexOf("All OK")

            If html.Contains("True") Then
                ResponseWebSite = "OK"

            ElseIf html.Contains("False") Then
                ResponseWebSite = "NOT OK"
            End If

        Catch
            ResponseWebSite = "Not Reachable"
        End Try

        Return ResponseWebSite

    End Function

    'Check if Attentnion is need to a specicifc server. 
    'wmi22.CheckAttention(Server.Text)
    Public Shared Function CheckAttenion(FullComputerName As String) As String
        Dim ResponseWebSite As String = " "
        Dim WebSiteLink As String
        Dim html As String = " "
        Try

            WebSiteLink = "http://" & FullComputerName.ToLower() & "/system/status.aspx"

            html = New TimedWebClient() With {.Timeout = 5000}.DownloadString(WebSiteLink)
        Catch generatedExceptionName As WebException
            WebSiteLink = "http://www." & FullComputerName.ToLower() & ".com/system/status.aspx"

            html = New TimedWebClient() With {.Timeout = 150000}.DownloadString(WebSiteLink)
        End Try

        Try


            Dim intPos As Integer = html.IndexOf("Needs Attention")

            If html.Contains("Yes") Then
                ResponseWebSite = "Yes"

            ElseIf html.Contains("No") Then
                ResponseWebSite = "No"
            End If

        Catch
            ResponseWebSite = "Not Reachable"
        End Try

        Return ResponseWebSite

    End Function

End Class

